package cn.com.cifi.mars.service.impl;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.com.cifi.mars.common.enums.LocalCommandEnum;
import cn.com.cifi.mars.common.enums.RedisChannelEnum;
import cn.com.cifi.mars.constant.Constants;
import cn.com.cifi.mars.constant.StageStatusEnum;
import cn.com.cifi.mars.entity.DmDmValueReport;
import cn.com.cifi.mars.mapper.mars.DmDmValueReportMapper;
import cn.com.cifi.mars.service.CacheService;
import cn.com.cifi.mars.service.DmDmValueReportService;
import cn.com.cifi.mars.util.DateUtils;
import cn.com.cifi.mars.util.SynchrolockUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 货值分析报表 服务实现类
 * </p>
 *
 * @author plx
 * @since 2020-02-19
 */
@Slf4j
@Service
public class DmDmValueReportServiceImpl extends ServiceImpl<DmDmValueReportMapper, DmDmValueReport> implements DmDmValueReportService {

    @Autowired
    private CacheService cacheService;

    @Autowired
    private SynchrolockUtil synchrolockUtil;

    /**
     * 同步货值数据
     * @param endDate 如 2020-02
     */
    @Override
    public void sync(String endDate,String... status) {
        boolean isLocked = synchrolockUtil.islocked(Constants.RedisSyncKey);
        try {
        	//同步货值信息数据留存
            baseMapper.removeDmDmValueReportLast();
            baseMapper.insertDmDmValueReportLast(endDate);
        	
            log.info("同步/计算全盘货值开始，截止日期：{}",endDate);
            String[] endDateArr = endDate.split("-");
            //同步数据
            String endTime = DateUtils.toEndTimeStr(endDate);
            if (status == null || status.length == 0){
                status = new String[]{StageStatusEnum.CTIVE.getKey()};
            }
            baseMapper.insertSync(endDate,endDateArr[0],endDateArr[1],endTime, Arrays.asList(status));
            log.info("同步/计算全盘货值结束，截止日期：{}",endDate);

            String localEndDate = LocalDate.now().format(DateTimeFormatter.ofPattern(DateUtils.DATE_JFP_STR));
            if (localEndDate.equals(endDate)){
                cacheService.pushCommand(RedisChannelEnum.CHANNEL_REMOVAL,LocalCommandEnum.FLUSH_REMOVAL_REPORT_CACHE);
            }
        } finally {
            synchrolockUtil.unlock(Constants.RedisSyncKey);
        }
    }

    @Override
    public String getLatestEndDate(String endDate) {
        QueryWrapper<DmDmValueReport> endDateWrapper = new QueryWrapper<>();
        endDateWrapper.select("max(end_date) endDate").le("end_date",endDate);
        DmDmValueReport endDateObj = getOne(endDateWrapper);
        if (endDateObj == null || endDateObj.getEndDate() == null){
            return null;
        }
        return endDateObj.getEndDate();
    }



}
